package service

import (
	"content_system/dao/db/content"
	"content_system/dao/def/content/model"
	"content_system/util"
	"content_system/value/dto"
	"context"
	"errors"
	"sync"
	"time"
)

var (
	contentServiceOnce sync.Once
	contentService     *ContentService
)

type ContentService struct {
}

func GetContentService() *ContentService {
	contentServiceOnce.Do(func() {
		contentService = &ContentService{}
	})
	return contentService
}

func (u *ContentService) Create(ctx context.Context, request *dto.ContentCreateRequest, uid int64) (*dto.ContentCreateResponse, error) {
	m := &model.Content{
		Title:       request.Title,
		Description: request.Description,
		VideoURL:    request.VideoURL,
		ThumbURL:    request.ThumbURL,
		Author:      uid,
		Status:      int32(model.ContentStatus_Pending),
		Extra:       util.MarshalString(&model.ContentExtra{}),
		IsDeleted:   false,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}
	err := content.GetContentDao().Create(ctx, m)
	if err != nil {
		return nil, err
	}
	return &dto.ContentCreateResponse{ContentID: m.ID}, nil
}

func (u *ContentService) Update(ctx context.Context, request *dto.ContentCreateRequest, uid int64) (*dto.ContentCreateResponse, error) {
	if request.ContentID == 0 {
		return &dto.ContentCreateResponse{ContentID: -1}, nil
	}
	r, err := content.GetContentDao().GetByID(ctx, request.ContentID)
	if err != nil {
		return nil, err
	}
	if r == nil {
		return &dto.ContentCreateResponse{ContentID: -1}, nil
	}
	if r.Author != uid {
		return nil, errors.New("user is not content‘s author")
	}
	err = content.GetContentDao().Update(ctx, request.ContentID, map[string]interface{}{
		"title":       request.Title,
		"description": request.Description,
		"video_url":   request.VideoURL,
		"thumb_url":   request.ThumbURL,
	})
	if err != nil {
		return nil, err
	}
	return &dto.ContentCreateResponse{ContentID: r.ID}, nil
}

func (u *ContentService) Delete(ctx context.Context, request *dto.ContentDeleteRequest, uid int64) error {
	if request.ContentID == 0 {
		return nil
	}
	r, err := content.GetContentDao().GetByID(ctx, request.ContentID)
	if err != nil {
		return err
	}
	if r == nil {
		return errors.New("content not exist")
	}
	if r.Author != uid {
		return errors.New("user is not content‘s author")
	}
	err = content.GetContentDao().Delete(ctx, request.ContentID)
	if err != nil {
		return err
	}
	return nil
}
